package cn.iocoder.yudao.module.search.framework.config;

import cn.iocoder.yudao.module.search.enums.SearchEngineTypeEnum;
import cn.iocoder.yudao.module.search.service.engine.SearchEngine;
import cn.iocoder.yudao.module.search.service.engine.impl.ZincSearchEngineImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * 搜索引擎配置类
 *
 * @author 芋道源码
 */
@Configuration
@EnableConfigurationProperties(SearchProperties.class)
@ConditionalOnProperty(prefix = "yudao.search", name = "enabled", havingValue = "true", matchIfMissing = true)
@Slf4j
public class SearchConfiguration {

    /**
     * 创建 WebClient Bean
     */
    @Bean
    public WebClient webClient() {
        return WebClient.builder().build();
    }

    /**
     * 创建搜索引擎实例
     */
    @Bean
    public SearchEngine searchEngine(SearchProperties searchProperties, WebClient webClient) {
        SearchEngineTypeEnum engineType = SearchEngineTypeEnum.getByType(searchProperties.getType());
        if (engineType == null) {
            throw new IllegalArgumentException("不支持的搜索引擎类型: " + searchProperties.getType());
        }

        log.info("[searchEngine][创建搜索引擎实例] type: {}", engineType.getName());

        switch (engineType) {
            case ZINCSEARCH:
                return new ZincSearchEngineImpl(searchProperties.getZincsearch(), webClient);
            case ELASTICSEARCH:
                // TODO: 实现 Elasticsearch 适配器
                throw new UnsupportedOperationException("Elasticsearch 适配器尚未实现");
            case OPENSEARCH:
                // TODO: 实现 OpenSearch 适配器
                throw new UnsupportedOperationException("OpenSearch 适配器尚未实现");
            case MEILISEARCH:
                // TODO: 实现 MeiliSearch 适配器
                throw new UnsupportedOperationException("MeiliSearch 适配器尚未实现");
            default:
                throw new IllegalArgumentException("不支持的搜索引擎类型: " + engineType);
        }
    }

}
